package com.express.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.express.core.mapper.OrdersMapper;
import com.express.dto.RoutingDto;
import com.express.dto.RoutingInfoDto;
import com.express.entity.RoutingInfos;
import com.express.entity.UserOrders;
import com.express.entity.UserReceipt;
import com.express.service.IRoutingInfosService;
import com.express.sys.mapper.RoutingInfosMapper;
import com.express.sys.mapper.UserRectiptMapper;
import com.express.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
public class RoutingInfosServiceImpl implements IRoutingInfosService {

    private static final Logger log = LoggerFactory.getLogger(RoutingInfosServiceImpl.class);

    @Autowired
    UserRectiptMapper rectiptMapper;
    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    private RoutingInfosMapper routingInfosMapper;

    @Override
    public List<RoutingInfos> list(RoutingInfoDto dto) {
        String orderNo = dto.getOrderNo();
        if (StringUtils.isBlank(orderNo)) {
            throw new RuntimeException("订单号不能空");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("oddNumber", orderNo);
        if (StringUtils.isBlank(dto.getOrderType())) {
            List<UserReceipt> userReceipts = rectiptMapper.queryList(map);
            if (userReceipts != null && userReceipts.size() > 0) {
                UserReceipt userReceipt = userReceipts.get(0);
                Integer id = userReceipt.getId();
                map.put("receiptId", id);
                return routingInfosMapper.queryList(map);
            }
        } else {
            List<UserOrders> userOrders = ordersMapper.getList(map);
            if (CollectionUtil.isNotEmpty(userOrders)) {
                UserOrders userOrder = userOrders.get(0);
                Integer id = userOrder.getId();
                map.put("receiptId", id);
                return routingInfosMapper.queryList(map);
            }
        }
        return null;
    }

    @Override
    public boolean save(RoutingDto routingDto) {
        if (routingDto == null) {
            return false;
        }
        try {
            if (routingDto.getRoutData() != null && routingDto.getRoutData().size() > 0) {
                routingDto.getRoutData().forEach(r -> {
                    if (StringUtils.isNotBlank(r.getAddr()) && StringUtils.isNotBlank(r.getStatus())) {
                        RoutingInfos routingInfos = new RoutingInfos();
                        routingInfos.setReceiptId(routingDto.getRecriptId());
                        routingInfos.setTranTime(r.getTranTime());
                        routingInfos.setAddr(r.getAddr());
                        routingInfos.setStatus(r.getStatus());
                        routingInfosMapper.save(routingInfos);
                    }
                });
            }
            if (StringUtils.isNotBlank(routingDto.getRoutingInfo())) {
                return saveRouting(routingDto.getRecriptId(), routingDto.getRoutingInfo());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public boolean saveRouting(Integer reciptId, String routingInfo) {
        try {
            // 先删除旧的
            Map<String, RoutingInfos> infosMap = new HashMap<>();
            if (reciptId != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("receiptId", reciptId);
                List<RoutingInfos> routingInfos1 = routingInfosMapper.queryList(map);
                List<Integer> ids = new ArrayList<>();
                if (routingInfos1 != null && routingInfos1.size() > 0) {
                    for (RoutingInfos routingInfos : routingInfos1) {
                        ids.add(routingInfos.getId());
                        String key = routingInfos.getStatus() + ":" + DateUtils.matter1.format(routingInfos.getTranTime());
                        infosMap.put(key, routingInfos);
                    }
//                    routingInfosMapper.deleteByIds(ids);
                }
            }
            String[] lines = routingInfo.split("\\n\\n");
            // 添加路由信息
            if (null != lines && lines.length > 0) {
                boolean statusFlag = false;
                boolean contenflag = false;
                RoutingInfos routingInfos = null;
                for (String line : lines) {
                    if (StringUtils.isBlank(line.trim())) {
                        statusFlag = false;
                        contenflag = false;
                        routingInfos = null;
                        continue;
                    }
                    if (StringUtils.isNotBlank(line) && !statusFlag) {
                        routingInfos = new RoutingInfos();
                        statusFlag = true;
                        routingInfos.setStatus(line);
                    } else if (statusFlag && StringUtils.isNotBlank(line) && !contenflag) {
                        contenflag = true;
                        System.out.println(line);
                        routingInfos.setReceiptId(reciptId);
                        routingInfos.setTranTime(DateUtils.matter5.parse(line.substring(0, 16)));
                        routingInfos.setAddr(line.substring(17));
                        String key = routingInfos.getStatus() + ":" + DateUtils.matter1.format(routingInfos.getTranTime());
                        // 检查是否已经录入
                        if (!infosMap.containsKey(key)) {
                            routingInfosMapper.save(routingInfos);
                        }
                        statusFlag = false;
                        contenflag = false;
                        routingInfos = null;
                    }
                }
            }
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public boolean updateById(RoutingInfos routingInfos) {
        return routingInfosMapper.update(routingInfos) > 0;
    }
}